package com.kg.fiber.service.security;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import lombok.extern.log4j.Log4j;

@Component
@Log4j
public class SecurityUserDetailsService implements UserDetailsService {
	
	public static final String UserName = "admin";


	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		
		if(!UserName.equals(username))
			throw new UsernameNotFoundException("用户[" + username + "]不存在");
		
		SecurityConfig config = SecurityConfig.instance.get();
		
		UserDetails userDetails = null;
		try {
			Collection<GrantedAuthority> authList = getAuthorities();
			userDetails = new User(username, config.getAccessPassword(),true,true,true,true,authList);
		} catch (Exception e) {
			log.error("Create user failed.", e);
		}
		
		return userDetails;
	}
	
	/**
	 * 获取用户的角色权限,为了降低实验的难度，这里去掉了根据用户名获取角色的步骤
	 * @param 
	 * @return
	 */
	private Collection<GrantedAuthority> getAuthorities(){
		List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>();  
		authList.add(new SimpleGrantedAuthority("ROLE_USER")); 
		authList.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
		return authList;
	}	

}

